#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct list_head
{
	struct list_head *next;
	struct list_head *prev;
};

/*初始化一个结点*/
#define INIT_LIST_HEAD(ptr) do{\
	(ptr)->next = (ptr);\
	(ptr)->prev = (ptr);\
}while(0)
	
/*在prev与next之前插入new*/
static void __list_add(struct list_head *new,
						struct list_head *prev,
						struct list_head *next)
{
	next->prev = new;
	new->next = next;
	new->prev = prev;
	prev->next = new;
}

/*在head和head->next之间插入new*/
static void list_add(struct list_head *new, struct list_head *head)
{
	__list_add(new, head, head->next);
}

/*在head->prev与head之间插入new*/
static void list_add_tail(struct list_head *new, struct list_head *head)
{
	__list_add(new, head->prev, head);
}

/*删除两个结点间的结点*/
static void __list_del(struct list_head *prev, struct list_head *next)
{
	next->prev = prev;
	prev->next = next;
}

/*删除entry结点*/
static void list_del(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
}

/*获取宿主结构体*/
#define offsetof(type, member) ((unsigned long)&(((type*)0)->member))
#define list_entry(ptr, type, member)   (type*)((char*)(ptr) - offsetof(type, member))

/*前向遍历*/
#define list_for_each(pos, head) \
	for(pos = (head)->next ; pos != (head); pos = pos->next)

#define list_for_each_safe(pos, n, head) \
	for(pos = (head)->next, n = pos->next; pos != (head); pos = n, n = pos->next)
/*自定义一个宿主结构体*/
struct node
{
	int data;
	struct list_head list; /*指针域*/
};
typedef struct node struData_t;
		
int main()
{
	int i = 0;
	struData_t *p = NULL;
	struct list_head *pos = NULL;
	
	struct list_head list;	/*创建链表头并初始化，只能在main函数中使用*/
	INIT_LIST_HEAD(&list);  //list.next = &list; list.prev = &list;
	
	for(i = 0; i < 10; i++)
	{
		p = (struData_t *)malloc(sizeof(struData_t));
		p->data = i;
		list_add_tail(&(p->list), &list);
	}
	
	list_for_each(pos, &list)
	{
		p = list_entry(pos, struData_t, list); /*获取了宿主结构体的地址*/
		printf("%d ", p->data);
	}

	list_for_each_safe()
	printf("\n");
	
}

















